import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt

data = sio.loadmat('ex6data1.mat')

X, y = data['X'], data['y']
print(X.shape)
# (51, 2)
print(y.shape)
# (51, 1)


def plot_data():
    plt.scatter(X[:, 0], X[:, 1], c=y.flatten(), cmap='jet')
    plt.xlabel('x1')
    plt.ylabel('y1')
    plt.show()

plot_data()


from sklearn.svm import SVC

svc1 = SVC(C=1, kernel='linear')
svc1.fit(X, y.flatten())

# 进行预测
print(svc1.predict(X))
# [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#  0 0 0 0 0 0 0 0 0 0 0 0 0 0]

print(svc1.score(X, y.flatten()))
# 得分：0.9803921568627451

# 绘制决策边界
def plot_boundary(model):  # 传入训练好的模型
    x_min, x_max = -0.5, 4.5
    y_min, y_max = 1.3, 5
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 500),
                         np.linspace(y_min, y_max, 500))
    z = model.predict(np.c_[xx.flatten(), yy.flatten()])
    zz = z.reshape(xx.shape)
    plt.contour(xx, yy, zz)


plot_boundary(svc1)
plot_data()


# 修改C
svc100 = SVC(C=100, kernel='linear')
svc100.fit(X, y.flatten())
# 预测
print(svc100.predict(X))
# [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#  0 0 0 0 0 0 0 0 0 0 0 0 0 1]
print(svc100.score(X, y.flatten()))
# 得分：1.0

# 绘制决策边界
plot_boundary(svc100)
plot_data()

